package com.zhss.redis.expire;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;


/**
 * 时间发布演示, 分布式锁
 *
 * @author winston
 * @date 2021/11/09
 */
public class TimeOutReleaseDemo {
	HostAndPort hostAndPort = new HostAndPort("121.4.79.149", 6379);
	Jedis jedis = new Jedis(hostAndPort);

	public static void main(String[] args) {
		TimeOutReleaseDemo demo = new TimeOutReleaseDemo();
		demo.jedis.setnx("lock_1", String.valueOf(1));
		demo.jedis.expire("lock_1", 60);

	}

	public boolean unlock(String key) {
		TimeOutReleaseDemo demo = new TimeOutReleaseDemo();

		Pipeline pipelined = demo.jedis.pipelined();
		try {
			pipelined.watch(key);
			Response<String> response = pipelined.get(key);
			if (response == null) {
				return true;
			}
			pipelined.multi();//开启事务
			pipelined.del(key);
			pipelined.exec();//执行
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally {
			pipelined.close();
		}
	}
}
